package ObjectMethodTest;
/*
equals()源代码
    public boolean equals(Object obj) {
            return (this == obj);
        }
作用
    通过equals方法来判断两个对象是否相等
 */
public class EqualsMethodTest1 {
    public static void main(String[] args){
        int a = 100;
        int b = 100;
        System.out.println(a == b);  // true相等 false不相等
        MyTime1 m1 = new MyTime1(2000,1,3);
        MyTime1 m2 = new MyTime1(2000,1,3);
        MyTime1 m3 = new MyTime1(2000,1,4);
        System.out.println(m1 == m2); //false 这里比较的是对象的内存地址
        //比较两个对象是否相等，应该用重写后的equals方法，比较内容
        boolean flag = m1.equals(m2);  //true
        boolean flag1 = m1.equals(m3); //false
        System.out.println(flag);
        System.out.println(flag1);
    }
}
class MyTime1{
    private int year;
    private int month;
    private int day;
    public MyTime1(){

    }
    public MyTime1(int year,int month,int day){
        this.year = year;
        this.month = month;
        this.day =day;
    }
    public String toString(){
        return this.year+"年"+this.month+"月"+this.day+"日";

    }
    //重写equals方法
    public boolean equals(Object o) {
        if(o == null || !(o instanceof MyTime1)){       //如果o为空，则直接返回false,如果o不是一个MyTime1对象，则直接返回false
            return false;
        }
        if(o == this){            //如果this和o保存的内存地址相等，则直接返回true
            return true;
        }
        //程序能执行到这说明o是一个MyTime1对象
        MyTime1 m = (MyTime1)o;
        //改良
        return (this.year == m.year && this.month == m.month && this.day == m.day);
    }
}